#! /usr/bin/env python3
# -*- coding:UTF-8 -*-
"""
@Project:   Selenium
@FileName:  remote_control.py
@Create:    2023/9/26 20:09
@Version:   Python3.9  
@Author:    Jia  
@Descr:     ->演示selenium控制已经打开的chrome浏览器操作页面

1，参考地址：https://blog.csdn.net/crhnb/article/details/131315515
2，chrome浏览器右键属性-->目标地址，后面加空格再加上以下参数
--remote-debugging-port=9222 --user-data-dir="C:\Users\Administrator\....\User Data"
3，打开浏览器输入chrome://version 查找--user-data-dir
4，端口号可以自己修改
"""
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchWindowException, NoSuchElementException, TimeoutException
from selenium import webdriver
from time import sleep


class SpaceSwap:
    def __init__(self):
        """初始化 driver"""

        option = Options()
        # 远程连接
        option.add_experimental_option("debuggerAddress", "127.0.0.1:9222")

        # 防止检测到selenium
        option.add_argument("--disable-blink-features")
        option.add_argument("--disable-blink-features=AutomationControlled")

        # 指定service路径
        s = Service(executable_path='./chromedriver.exe')
        self.driver = webdriver.Chrome(service=s, options=option)
        self.driver.implicitly_wait(3)

    def execute_space(self, eth_num: str, usdc_num: str):
        # 切换到chrome浏览器
        self.driver.switch_to.window(self.driver.window_handles[-1])
        try:
            # 新窗口打开space swap
            self.driver.execute_script("window.open('https://swap-zksync.spacefi.io/#/swap');")
            self.driver.switch_to.window(self.driver.window_handles[-1])
            print('进入了space swap')
            txz_xpath = '//*[@id="swap-currency-output"]/div/div[2]/button'
            WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.XPATH, txz_xpath)))
        except (TimeoutException, NoSuchWindowException):
            print('没有发现 通行证，将刷新重试')
            self.driver.refresh()
            sleep(3)
        try:
            # 点击通行证
            txz = self.driver.find_element(By.XPATH, '//*[@id="swap-currency-output"]/div/div[2]/button')
            # 按钮背景变红
            self.driver.execute_script("arguments[0].style.backgroundColor = 'red';", txz)
            txz.click()
            print('点击 通行证')
            sleep(2)
            # 按钮恢复原始样式
            self.driver.execute_script("arguments[0].setAttribute('style', arguments[1]);", txz, "")
        except (NoSuchWindowException, NoSuchElementException):
            print('没有发现 通行证, 需要重新启动')
            self.driver.close()
            self.driver.quit()
        try:
            # 点击 USDC
            usdc_xpath = '/html/body/reach-portal[1]/div[3]/div/div/div/div/div[1]/div[2]/div[2]/div[4]'
            self.driver.find_element(By.XPATH, usdc_xpath).click()
            sleep(2)
        except (NoSuchWindowException, NoSuchElementException):
            print('没有发现 usdc')

        """ETH 交换"""
        if eth_num != '':
            try:
                # 输入ETH要转换的数量
                self.driver.find_element(By.XPATH, '//*[@id="swap-currency-input"]/div/div[2]/input').send_keys(eth_num)
                sleep(2)
                # 点击 SWAP
                swap_but = self.driver.find_element(By.XPATH, '//*[@id="swap-button"]')
                self.driver.execute_script("arguments[0].style.backgroundColor = 'red';", swap_but)
                swap_but.click()
                self.driver.execute_script("arguments[0].setAttribute('style', arguments[1]);", swap_but, "")
                sleep(2)
            except (NoSuchWindowException, NoSuchElementException):
                print('没有发现 swap button')
            try:
                # 点击 同意
                confirm_but = self.driver.find_element(By.XPATH, '//*[@id="confirm-swap-or-send"]')
                self.driver.execute_script("arguments[0].style.backgroundColor = 'red';", confirm_but)
                confirm_but.click()
                # self.driver.execute_script("arguments[0].setAttribute('style', arguments[1]);", confirm_but, "")
                print('点击 confirm button')
                sleep(3)

                # 切换到钱包小窗口
                self.driver.switch_to.window(self.driver.window_handles[-1])
                print('切换到钱包小窗口，准备点击 确认')
            except (NoSuchWindowException, NoSuchElementException):
                print('没有发现 confirm button')
            try:
                # 等待钱包小窗口中的 确认出现 并点击
                confirm_xpath = '//*[@id="app-content"]/div/div/div/div[3]/div[3]/footer/button[2]'
                WebDriverWait(self.driver, 8).until(EC.presence_of_element_located((By.XPATH, confirm_xpath)))
                confirm = self.driver.find_element(By.XPATH, confirm_xpath)
                self.driver.execute_script("arguments[0].scrollIntoView();", confirm)
                confirm.click()
                sleep(2)
            except (NoSuchWindowException, NoSuchElementException, TimeoutException):
                print('没有发现钱包小窗口中的 确认按钮')

            try:
                # 切换回 space swap 窗口
                self.driver.switch_to.window(self.driver.window_handles[-1])
                # 点击 close
                close_xpath = '/html/body/reach-portal[5]/div[3]/div/div/div/div/div/div[3]/button[2]'
                self.driver.find_element(By.XPATH, close_xpath).click()
                print('点击 close, 3秒后关闭窗口')
                sleep(3)
                self.driver.close()
            except (NoSuchWindowException, NoSuchElementException):
                print('没有出现 close, 3秒后关闭窗口')
                sleep(3)
                self.driver.close()
        else:
            print('ETH为0，不需要交换')

        if usdc_num != '':
            try:
                # 切换为USDC to ETH
                self.driver.find_element(By.CSS_SELECTOR,
                                    '#swap-page > div.sc-ckVGcZ.bgrLUl > div.sc-ckVGcZ.fgzRPw > div > div > svg').click()
                print('切换为USDC to ETH')
                sleep(1)
                # 输入 usdc_num
                self.driver.find_element(By.XPATH, '//*[@id="swap-currency-input"]/div/div[2]/input').send_keys(usdc_num)
            except (NoSuchWindowException, NoSuchElementException):
                print('没有输入 usdc_num')

            try:
                # 等待SWAP出现后 点击
                WebDriverWait(self.driver, 6).until(EC.presence_of_element_located((By.XPATH, '//*[@id="swap-button"]')))
                swap_but2 = self.driver.find_element(By.XPATH, '//*[@id="swap-button"]')
                self.driver.execute_script("arguments[0].style.backgroundColor = 'red';", swap_but2)
                self.driver.find_element(By.XPATH, '//*[@id="swap-button"]').click()
                print('click swap button')
                sleep(2)

                # 点击 confirm swap
                confirm_but2 = self.driver.find_element(By.XPATH, '//*[@id="confirm-swap-or-send"]')
                self.driver.execute_script("arguments[0].style.backgroundColor = 'red';", confirm_but2)
                confirm_but2.click()
                print('点击 confirm swap')
                sleep(3)
            except (NoSuchWindowException, NoSuchElementException, TimeoutException):
                print('没有发现swap 和 confirm swap')

            try:
                # 再次切换到钱包小窗口
                self.driver.switch_to.window(self.driver.window_handles[-1])
                # 点击钱包窗口中的 确认
                confirm_xpath2 = '//*[@id="app-content"]/div/div/div/div[3]/div[3]/footer/button[2]'
                WebDriverWait(self.driver, 8).until(EC.presence_of_element_located((By.XPATH, confirm_xpath2)))
                self.driver.find_element(By.XPATH, confirm_xpath2).click()
                sleep(2)
            except (NoSuchWindowException, NoSuchElementException, TimeoutException):
                print('没有发现钱包窗口的确认')
            try:
                # 切换回 space swap 窗口
                self.driver.switch_to.window(self.driver.window_handles[-1])
                # 点击 close
                close_xpath = '/html/body/reach-portal[5]/div[3]/div/div/div/div/div/div[3]/button[2]'
                self.driver.find_element(By.XPATH, close_xpath).click()
                print('点击 close， 3秒后关闭窗口')
                sleep(3)
                self.driver.close()
            except (NoSuchWindowException, NoSuchElementException):
                print('没有出现 close, 3秒后关闭窗口')
                sleep(3)
                self.driver.close()
